import java.util.*;

public class Solution210 {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] first=new int[numCourses];
        Arrays.fill(first,-1);
        int[] next=new int[prerequisites.length];
        int[] go=new int[prerequisites.length];
        int[] du=new int[numCourses];
        for (int i=0;i<prerequisites.length;i++){
            next[i]=first[prerequisites[i][1]];
            first[prerequisites[i][1]]=i;
            go[i]=prerequisites[i][0];
            du[prerequisites[i][0]]++;
        }
        Queue<Integer> queue=new LinkedList<>();
        for (int i=0;i<numCourses;i++){
            if (du[i]==0){
                queue.offer(i);
            }
        }
        List<Integer> list=new ArrayList<>();
        while (!queue.isEmpty()){
            int t=queue.poll();
            list.add(t);
            t=first[t];
            while (t!=-1){
                du[go[t]]--;
                if (du[go[t]]==0){
                    queue.offer(go[t]);
                }
                t=next[t];
            }
        }
        if (list.size()!=numCourses){
            return new int[0];
        }else{
            int[] ans=new int[numCourses];
            for (int i=0;i<numCourses;i++){
                ans[i]=list.get(i);
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution210().findOrder(2, new int[][]{{1, 0}})));
    }
}
